package org.vacoor.xqq.hotkey.impl.linux;

import jxgrabkey.HotkeyConflictException;
import jxgrabkey.HotkeyListener;
import jxgrabkey.JXGrabKey;
import org.vacoor.xqq.hotkey.AbstractOSHotKeyBinder;
import org.vacoor.xqq.hotkey.OSHotKeyConflictException;
import org.vacoor.xqq.hotkey.OSHotKeyEvent;
import org.vacoor.xqq.hotkey.OSHotKeyListener;

/**
 * User: Vacoor
 */
class JXGrabKeyBinder extends AbstractOSHotKeyBinder implements HotkeyListener {
    private JXGrabKey jxGrabKey;
    private boolean conflict;

    public JXGrabKeyBinder(JXGrabKey jxGrabKey, int identifier) {
        super(identifier);
        this.jxGrabKey = jxGrabKey;
    }

    @Override
    public void setHotKey(int midifier, int key) throws OSHotKeyConflictException {
        super.setHotKey(midifier, key);
        try {
            jxGrabKey.removeHotkeyListener(this);
            jxGrabKey.registerAwtHotkey(getIdentifier(), midifier, key);
            jxGrabKey.addHotkeyListener(this);
            conflict = false;
        } catch (HotkeyConflictException e) {
            conflict = true;
            throw new OSHotKeyConflictException(e);
        }
    }

    @Override
    public boolean isConflict() {
        return conflict;
    }

    /**
     * JXGrabKey 回调
     */
    @Override
    public void onHotkey(int i) {
        if (getIdentifier() == i) {
            for (OSHotKeyListener l : getOSHotKeyListeners()) {
                l.onOSHotKey(new OSHotKeyEvent(getIdentifier(), getMidifier(), getKey()));
            }
        }
    }
}
